package com.iagent.spring.boot;

import com.iagent.request.RequestConfig;
import com.iagent.spring.IagentProxyBean;
import com.iagent.util.CollectionUtils;
import com.iagent.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Iagent Spring Boot Auto Configuration
 * @see IagentProxyBean
 * @since 1.0.0
 */
@Configuration
@EnableConfigurationProperties(IagentProperties.class)
@ConditionalOnProperty(prefix = "iagent", value = "enabled",matchIfMissing = true)
public class IagentAutoConfiguration {

    @Autowired
    private IagentProperties properties;

    @Bean(name = IagentProxyBean.SPRING_BOOT_IAGENT_FACTORY_NAME)
    @ConditionalOnMissingBean
    public IagentProxyBean iagentProxyBean() {
        IagentProxyBean iagentProxyBean = new IagentProxyBean();
        if (properties.getJsonSupport() != null) {
            iagentProxyBean.setJsonSupportClass(properties.getJsonSupport());
        }
        if (properties.getLogImpl() != null) {
            iagentProxyBean.setLogImplClass(properties.getLogImpl());
        }
        if (properties.getRequestConfig() != null) {
            IagentProperties.RequestConfig requestConfig = properties.getRequestConfig();
            RequestConfig config = new RequestConfig();
            config.setHttpExecutor(requestConfig.getHttpExecutor());
            config.setRequestType(requestConfig.getRequestType());
            config.setContentType(requestConfig.getContentType());
            config.setReadTime(requestConfig.getReadTime());
            config.setConnectionTime(requestConfig.getConnectionTime());
            iagentProxyBean.setRequestConfig(config);
        }
        if (CollectionUtils.isNotEmpty(properties.getAddParameterResolvers())) {
            iagentProxyBean.addParameterResolvers(properties.getAddParameterResolvers());
        }
        if (CollectionUtils.isNotEmpty(properties.getAddResultResolvers())) {
            iagentProxyBean.addResultResolvers(properties.getAddResultResolvers());
        }
        if (CollectionUtils.isNotEmpty(properties.getPlugins())) {
            iagentProxyBean.setPluginClass(properties.getPlugins());
        }
        if (properties.getBannerMode() != null) {
            iagentProxyBean.setBannerMode(properties.getBannerMode());
        }
        return iagentProxyBean;
    }

}
